package com.zero.basic.dao;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.zero.basic.model.Pager;

@Repository("sqlPagingListBaseDao")
public class SqlPagingListBaseDao<T> extends DefaultBaseDao<T> {
	/**
	 * 
	 * @param sql
	 * @param args
	 * @param clz
	 * @param hasEntity
	 * @return
	 */
	public <N extends Object> Pager<N> findBySql(String sql, Object[] args,
			Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, args, null, clz, hasEntity);
	}

	public <N extends Object> Pager<N> findBySql(String sql, Object arg,
			Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, new Object[] { arg }, clz, hasEntity);
	}

	public <N extends Object> Pager<N> findBySql(String sql, Class<?> clz,
			boolean hasEntity) {
		return this.findBySql(sql, null, clz, hasEntity);
	}

	@SuppressWarnings("unchecked")
	public <N extends Object> Pager<N> findBySql(String sql, Object[] args,
			Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		sql = initSort(sql);
		String cq = getCountHql(sql, false);
		SQLQuery sq = getSession().createSQLQuery(sql);
		SQLQuery cquery = getSession().createSQLQuery(cq);
		setAliasParameter(sq, alias);
		setAliasParameter(cquery, alias);
		setParameter(sq, args);
		setParameter(cquery, args);
		Pager<N> pages = new Pager<N>();
		setPagers(sq, pages);
		if (hasEntity) {
			sq.addEntity(clz);
		} else {
			sq.setResultTransformer(Transformers.aliasToBean(clz));
		}
		List<N> datas = sq.list();
		pages.setDatas(datas);
		long total = ((BigInteger) cquery.uniqueResult()).longValue();
		pages.setTotal(total);
		return pages;
	}

	public <N extends Object> Pager<N> findByAliasSql(String sql,
			Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, null, alias, clz, hasEntity);
	}
}